package top.lyc829.aircontroller.logic.utils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class HttpUtils {

    public final static int SUCCESS = 0;
    public final static int FAIL = 1;
    public final static int MODE_LIST_STRING = 0;
    public final static int MODE_LIST_BEAN = 1;
    public final static int MODE_LIST_MAP = 2;

    private String url;
    private int mode;
    private Class<?> clazz;
    private List<String> keys;

    private HttpUtils(String url){
        this.url = url;
        this.mode = MODE_LIST_STRING;
    }

    public static HttpUtils create(String url){
        return new HttpUtils(url);
    }


    public HttpUtils setParams(Map<String,String> params){
        this.url += "?";
        for (String key : params.keySet()){
            this.url += (key + "=" + params.get(key) + "&");
        }
        return this;
    }

    public HttpUtils setRetBean(Class<?> clazz){
        this.mode = MODE_LIST_BEAN;
        this.clazz = clazz;
        return this;
    }

    public HttpUtils setRetBean(List<String> keys){
        this.mode = MODE_LIST_MAP;
        this.keys = keys;
        return this;
    }


    public void doGet(final CallBack callBack){
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callBack.returnInfo(FAIL,null,null);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                switch (mode){
                    case MODE_LIST_STRING:
                        JsonUtils.parseList(response.body().string(),callBack);
                        break;
                    case MODE_LIST_BEAN:
                        JsonUtils.parseBean(response.body().string(),clazz,callBack);
                        break;
                    case MODE_LIST_MAP:
                        JsonUtils.parseMap(response.body().string(),keys,callBack);
                        break;
                    default:
                        break;
                }
            }
        });
    }

}
